<!-- 会员管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 会员列表 -->
      <el-col :lg="24" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <el-form-item :label="$t('Keyword')" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                :placeholder="$t('Please_Enter') + ' ' + $t('Keyword')"
                clearable
              />
            </el-form-item>

            <el-form-item :label="$t('Status')" prop="status">
              <el-select
                v-model="queryParams.status"
                :placeholder="$t('All')"
                clearable
                style="width: 100px"
              >
                <el-option :label="$t('Normal')" :value="1" />
                <el-option :label="$t('Disable')" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">
                {{ $t("Search") }}
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                {{ $t("Reset") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar" style="margin-bottom: 10px">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['memberEdit']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                {{ $t("Add") }}
              </el-button>
              <el-button
                v-hasPerm="'memberDelBtn'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                {{ $t("Delete") }}
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            :selectable="selectable"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column :label="$t('Account_Information')" width="280">
              <template #default="scope">
                <div>
                  <div>{{ $t("Account") }}:{{ scope.row.username }}</div>
                  <div>{{ $t("Mobile") }}:{{ scope.row.phone }}</div>
                  <div>{{ $t("Nickname") }}:{{ scope.row.nick_name }}</div>
                  <div>{{ $t("Email") }}:{{ scope.row.email }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('Avatar')" width="80">
              <template #default="scope">
                <img :src="scope.row.head_img" alt="" style="width: 50px" />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('Promotion_Code')"
              prop="popularize_code"
              width="150"
            />
            <el-table-column
              :label="$t('Balance')"
              prop="balance"
              width="100"
            />
            <el-table-column
              :label="$t('Integral')"
              prop="integral"
              width="100"
            />
            <el-table-column :label="$t('Gender')" width="80">
              <template #default="scope">
                <el-tag
                  :type="scope.row.grender === 1 ? 'success' : 'danger'"
                  disable-transitions
                >
                  {{ scope.row.grender === 1 ? $t("Male") : $t("Female") }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column :label="$t('Login_Information')" width="300">
              <template #default="scope">
                <div>
                  <div>{{ $t("Login_Num") }}:{{ scope.row.login_num }}</div>
                  <div>{{ $t("Login_IP") }}:{{ scope.row.login_last_ip }}</div>
                  <div>
                    {{ $t("Login_Time") }}:{{ scope.row.login_last_at }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('Status')">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 1 ? 'success' : 'danger'"
                  disable-transitions
                >
                  {{ scope.row.status === 1 ? $t("Normal") : $t("Disable") }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- 显示时间戳 -->
            <el-table-column
              :label="$t('Create_Time')"
              align="center"
              prop="created_at"
              width="200"
            />
            <el-table-column
              :label="$t('Update_Time')"
              align="center"
              prop="updated_at"
              width="200"
            />
            <el-table-column
              :label="$t('Operate')"
              fixed="right"
              align="center"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="'memberEdit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  {{ $t("Edit") }}
                </el-button>
                <el-button
                  v-hasPerm="'memberDelBtn'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  {{ $t("Delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[15, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="130px"
      >
        <el-form-item :label="$t('Account')" prop="username">
          <el-input
            v-model="formData.username"
            :placeholder="$t('Please_Enter') + $t('Account')"
          />
        </el-form-item>
        <el-form-item :label="$t('Password')" prop="password">
          <el-input
            v-model="formData.password"
            :placeholder="$t('Please_Enter') + $t('Password')"
          />
        </el-form-item>
        <el-form-item :label="$t('Mobile')" prop="phone">
          <el-input
            v-model="formData.phone"
            :placeholder="$t('Please_Enter') + $t('Mobile')"
          />
        </el-form-item>
        <el-form-item :label="$t('Email')" prop="email">
          <el-input
            v-model="formData.email"
            :placeholder="$t('Please_Enter') + $t('Email')"
          />
        </el-form-item>
        <el-form-item :label="$t('Nickname')" prop="nick_name">
          <el-input
            v-model="formData.nick_name"
            :placeholder="$t('Please_Enter') + $t('Nickname')"
          />
        </el-form-item>
        <el-form-item :label="$t('Avatar')" prop="head_img">
          <SingleImageUpload v-model="formData.head_img" />
        </el-form-item>
        <el-form-item :label="$t('Gender')" prop="grender">
          <el-radio-group v-model="formData.grender">
            <el-radio :label="1">{{ $t("Male") }}</el-radio>
            <el-radio :label="2">{{ $t("Female") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('Status')" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">{{ $t("Normal") }}</el-radio>
            <el-radio :label="2">{{ $t("Disable") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">
            {{ $t("Confirm") }}
          </el-button>
          <el-button @click="handleCloseDialog">{{ $t("Cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import i18n from "@/lang/index";
import MemberAPI, {
  MemberListVO,
  MemberList,
  MemberInfo,
  MemberData,
  MemberPageQuery,
} from "@/api/system/member.api";
defineOptions({
  name: "Member",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive<MemberPageQuery>({
  page: 1,
  pageSize: 15,
});
const selectable = (row: MemberInfo) => ![1].includes(Number(row.id));
const pageData = ref<MemberList[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: i18n.global.t("Add") + i18n.global.t("Member"),
});

const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);

let formData = reactive<MemberData>({
  id: "",
  username: "",
  password: "",
  phone: "",
  email: "",
  grender: 0,
  nick_name: "",
  head_img: "",
  status: 0,
  level_id: 0,
});

const rules = reactive({
  username: [
    {
      required: true,
      message: i18n.global.t("Account") + i18n.global.t("Not_Empty"),
      trigger: "blur",
    },
  ],
});

// 选中的会员ID
const selectIds = ref<number[]>([]);
// 查询
async function handleQuery() {
  loading.value = true;
  MemberAPI.getPage(queryParams)
    .then((data: MemberListVO) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.page = 1;
  queryParams.keywords = "";
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 会员ID
 */
async function handleOpenDialog(data?: MemberInfo) {
  dialog.visible = true;
  if (data?.id) {
    dialog.title = i18n.global.t("Edit") + i18n.global.t("Member");
    console.log(data);
    Object.assign(formData, data);
  } else {
    dialog.title = i18n.global.t("Add") + i18n.global.t("Member");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  dialog.visible = false;
  formData.id = "";
  formData.username = "";
  formData.password = "";
  formData.phone = "";
  formData.email = "";
  formData.grender = 1;
  formData.nick_name = "";
  formData.head_img = "";
  formData.status = 1;
}

// 提交会员表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        MemberAPI.update(formData)
          .then(() => {
            ElMessage.success(i18n.global.t("Operate_Success"));
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MemberAPI.create(formData)
          .then(() => {
            ElMessage.success(i18n.global.t("Operate_Success"));
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除会员
 *
 * @param id  会员ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning(i18n.global.t("Please_Select_Delete_Item"));
    return;
  }
  ElMessageBox.confirm(
    i18n.global.t("Confirm_Delete"),
    i18n.global.t("Warning"),
    {
      confirmButtonText: i18n.global.t("Confirm"),
      cancelButtonText: i18n.global.t("Cancel"),
      type: "warning",
    }
  ).then(
    function () {
      loading.value = true;
      MemberAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success(i18n.global.t("Operate_Success"));
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info(i18n.global.t("Operate_Cancel"));
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
